package pwr.online.cow;

import pwr.online.cow.model.Board;
import pwr.online.cow.model.Position;
import pwr.online.cow.model.Position2D;

public class CowSearchAlgorithm2D extends CowSearchAlgorithm implements BoardControllerListener {
	private int mMoveLimit;
	private int mMoveCount;
	int mSideEnlonger;
	private int nextX, nextY;
	private int startXDirection;
	private int startYDirection;
	private Position2D mNextPosition;
	
	public CowSearchAlgorithm2D(Board board, Position cowPosition) {
		super(board, cowPosition);
		startXDirection = 1;
		startYDirection = 0;
		mMoveCount = 1;
		mMoveLimit = 2;
		nextX = 1;
		nextY = 0;
		mSideEnlonger = 0;
		mNextPosition = (Position2D)getInitialPosition();
	}

	@Override
	public Position getNewPosition() {
		mNextPosition = new Position2D(mNextPosition.getX()+nextX,
				mNextPosition.getY() + nextY);

		mMoveCount++;
	
		if (mMoveCount >= mMoveLimit) {
			mMoveCount = 1;
			mMoveLimit += (mSideEnlonger % 2);
			mSideEnlonger++;
			mSideEnlonger %= 2;
			if (nextX == 1 && nextY == 0) {
				nextX = 0;
				nextY = -1;
			} else if (nextX == 0 && nextY == -1) {
				nextX = -1;
				nextY = 0;
			} else if (nextX == -1 && nextY == 0) {
				nextX = 0;
				nextY = 1;
			} else if (nextX == 0 && nextY == 1) {
				nextX = 1;
				nextY = 0;
			}
		}
		
		return mNextPosition;
	}

	@Override
	public Position getInitialPosition() {
		return new Position2D(Board2DView.CELLS_HORIZONTAL/2, Board2DView.CELLS_VERTICAL/2);
	}

	@Override
	public void reset() {
		mMoveCount = 1;
		mMoveLimit = 2;
		nextX = startXDirection;
		nextY = startYDirection;
		mSideEnlonger = 0;
		mNextPosition = (Position2D)getInitialPosition();
		mBoard.addHistoryEntry(getInitialPosition());
	}

	@Override
	public void HistoryViewChanged(int newValue) {}

	@Override
	public void RestartAlgorithm() {}

	@Override
	public void NewStartDirection(int x, int y) {
		startXDirection = x;
		startYDirection = y;
	}

}
